package com.adv.ems.manager.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.adv.ems.db.mapper.ReportHourPoolMapper;
import com.adv.ems.db.entity.ReportHourPoolDO;
import com.adv.ems.manager.ReportHourPoolManager;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.*;

@Service
public class ReportHourPoolManagerImpl extends ServiceImpl<ReportHourPoolMapper, ReportHourPoolDO> implements ReportHourPoolManager {
    @Override
    public void saveOrUpdate(Long pointId, Date date) {
        boolean b = updateUpdateTime(pointId, date);
        if (!b) {
            ReportHourPoolDO reportHourPool = new ReportHourPoolDO();
            reportHourPool.setPointId(pointId);
            reportHourPool.setUpdateTime(new Date());
            reportHourPool.setCreateTime(new Date());
            reportHourPool.setTime(date);
            save(reportHourPool);
        }
    }

    @Override
    public List<ReportHourPoolDO> getRecentUnUpdateHourAndDel(Integer delayMinute, Integer pullDataSize) {
        long time = System.currentTimeMillis() - Duration.ofMinutes(delayMinute).toMillis();

        LambdaQueryWrapper<ReportHourPoolDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(ReportHourPoolDO::getUpdateTime, new Date(time));
        wrapper.orderByAsc(ReportHourPoolDO::getUpdateTime);
        wrapper.last("limit " + pullDataSize);
        List<ReportHourPoolDO> list = list(wrapper);
        if (CollectionUtil.isEmpty(list)) {
            return list;
        }
        list.forEach(l -> removeById(l.getId()));
        return list;
    }

    public boolean updateUpdateTime(Long pointId, Date hour) {
        LambdaQueryWrapper<ReportHourPoolDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportHourPoolDO::getPointId, pointId);
        wrapper.eq(ReportHourPoolDO :: getTime, hour);
        ReportHourPoolDO record = new ReportHourPoolDO();
        record.setUpdateTime(new Date());
        return update(record, wrapper);
    }
}
